package com.xiaomaoguai.fcp.pre.kepler.router.rpc.client.okhttp;

import okhttp3.Response;
import java.io.Serializable;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSONObject;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.exception.HttpResponseException;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.exception.HttpStatusCodeException;

/**
 * Http响应结果处理类
 */
public class HttpResponse implements Serializable {

	private static final long serialVersionUID = -279895125199990839L;

	private transient final Response okHttpResponse;


	public HttpResponse(Response okHttpResponse) {
		this.okHttpResponse = okHttpResponse;
	}
	
	/**
	 * 获取返回的指定header
	 * @param name
	 * @return
	 */
	public String header(String name) {
		return this.okHttpResponse.header(name);
	}

	/**
	 * http 状态消息
	 *
	 */
	public String message() {
		return okHttpResponse.message();
	}


	/**
	 * http 错误码
	 */
	public int code() {
		return okHttpResponse.code();
	}


	public Response response() {
		return okHttpResponse;
	}

	/**
	 * 将响应结果转为字符串
	 *
	 */
	public String asString() {
		assertSuccess();
		try {
			return okHttpResponse.body().string();
		} catch (Exception e) {
			throw new HttpResponseException(e);
		} finally {
			IOUtils.closeQuietly(this.okHttpResponse);
		}
	}

	/**
	 * 将响应结果转为JavaBean对象(仅限json字符串)
	 */
	public <T> T asBean(Class<T> clazz) {
		assertSuccess();
		try {
			return JSONObject.parseObject(okHttpResponse.body().string(), clazz);
		} catch (Exception e) {
			throw new HttpResponseException(e);
		} finally {
			IOUtils.closeQuietly(this.okHttpResponse);
		}
	}

	/**
	 * 将响应结果转为字节数组
	 */
	public byte[] asByteData() {
		assertSuccess();
		try {
			return okHttpResponse.body().bytes();
		} catch (Exception e) {
			throw new HttpResponseException(e);
		} finally {
			IOUtils.closeQuietly(this.okHttpResponse);
		}
	}

	public boolean isSuccess() {
		return okHttpResponse.isSuccessful();
	}

	private void assertSuccess() {
		if (!okHttpResponse.isSuccessful()) {
			throw new HttpStatusCodeException(this.okHttpResponse.request().url().toString(), code(),
					message());
		}
	}
}
